<template>
  <div>
    <div style="display: flex;padding: 1%" class="shadow">
      <div style="width: 70%">
        <el-input v-model="title" placeholder="请输入标题"></el-input>
      </div>
      <div style="width: 30%" align="right">
        <el-button @click="btn_postArticle(0)" v-if="!editFlag">丢到废纸篓</el-button>
        <el-button @click="btn_postArticle(1)" v-if="!editFlag">发布文章</el-button>
        <el-button @click="btn_postArticle(2)" v-if="editFlag">保存文章</el-button>
      </div>
    </div>
    <div style="margin-top: 2%">
      <mavon-editor v-model="content" :ishljs="true" ref="md" @imgAdd="$imgAdd" @imgDel="$imgDel" />
    </div>

    <div style="margin-top: 2%">
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <!--        添加标签-->
          <div class="shadow" style="padding: 2%;margin: 1%;margin-left: 0">
            <h3>加个标签吧</h3>
            <p>如果标签不存在的话,将会默认添加新的标签</p>
            <div style="display: flex ;margin-top: 5%">
              <div style="flex:1;">
                <el-tag
                  style="margin: 2%"
                  :key="tag.lid"
                  v-for="tag in dynamicTags"
                  closable
                  effect="dark"
                  :disable-transitions="false"
                  @close="handleClose(tag)"
                >{{tag.name}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新建</el-button>
              </div>
              <div style="flex:1;">
                <el-tag
                  style="margin:2%"
                  :key="item.label"
                  :type="item.type"
                  effect="plain"
                  @click="btn_tag(item)"
                  v-for="item in listOfTags"
                >{{item.name}}</el-tag>
              </div>
            </div>
          </div>ß
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <!--        添加分类-->
          <div style="padding: 2%;margin: 1%;margin-right: 0" class="shadow">
            <h3>加个分类吧</h3>
            <p>没有想要的分类,可以先添加哦</p>
            <div style="margin-top: 5%">
              <el-radio
                v-model="categoryButtons"
                :label="item.cid"
                border
                v-for="item in categoryList"
                :key="ißßtem.id"
              >{{item.name}}</el-radio>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
let that;
export default {
  name: "WriteAnEssay",
  data() {
    return {
      title: "",
      content: "",
      dynamicTags: [],
      tagID: "", //标签的id
      inputVisible: false,
      inputValue: "",
      listOfTags: [], //标签列表
      categoryButtons: 0, //分类按钮id
      categoryList: [], //分类列表

      //    下面的文章编辑所需的参数
      editFlag: false,
      aid: 0
    };
  },
  mounted() {
    that = this;
    //    获取所有的标签
    that
      .$Axios(that.$store)
      .post(that.LABEL_API + "/list")
      .then(function(result) {
        that.listOfTags = result.data.data;
      });

    //    获取所有的分类
    that
      .$Axios(that.$store)
      .post(that.CLASSIFICATION_API + "/list")
      .then(function(result) {
        that.categoryList = result.data.data;
      });

    //    接受传过来的文章id,并且编辑该文章
    let aid = that.$route.query.aid;
    if (aid != null) {
      that.aid = aid;
      that.editFlag = true;

      //获取文章的所有信息
      that
        .$Axios(that.$store)
        .get(that.ARTICLE_API + "/id/" + aid)
        .then(function(result) {
          let data = result.data.data;
          that.title = data.title;
          that.content = data.content;
          that.categoryButtons = data.classification;

          //获取当前文章的标签
          let label = data.label;
          that.tagID = label;
          let sub = label.split("|");
          sub.forEach(o => {
            that
              .$Axios(that.$store)
              .get(that.LABEL_API + "/id/" + o)
              .then(function(result) {
                let items = result.data.data;
                that.dynamicTags.push(items);
              });
          });
        });
    }
  },
  methods: {
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      formdata.append("image", $file);
      this.img_file[pos] = $file;
      this.Axios({
        url: "/api/edit/uploadimg",
        method: "post",
        data: formdata,
        headers: { "Content-Type": "multipart/form-data" }
      }).then(res => {
        let _res = res.data;
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        this.$refs.md.$img2Url(pos, _res.url);
      });
    },
    $imgDel(pos) {
      delete this.img_file[pos];
    },
    //删除一个标签
    //不会从数据库里面删除
    handleClose(tag) {
      let ts = this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      console.log(ts);
      let of = that.tagID.indexOf("|");
      let number = that.tagID.indexOf(tag.lid);
      if (of === -1) {
        that.tagID = "";
      } else {
        if (number === 0) {
          that.tagID = that.tagID.replace(tag.lid + "|", "");
        } else {
          that.tagID = that.tagID.replace("|" + tag.lid, "");
        }
      }
    },
    showInput() {
      this.inputVisible = true;
    },

    handleInputConfirm() {
      if (this.inputVisible && !(this.inputValue.trim() === "")) {
        //添加一个标签
        that
          .$Axios(that.$store)
          .put(that.LABEL_API + "/" + this.inputValue + "/")
          .then(function(result) {
            that.listOfTags = result.data.data;
          })
          .catch(function(result) {
            console.log(JSON.stringify(result));
          });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    //从已有的标签中添加
    btn_tag(item) {
      let number = that.dynamicTags.indexOf(item);
      if (number === -1) {
        that.dynamicTags.push(item);
        if (that.dynamicTags.length === 1) {
          that.tagID = that.tagID + item.lid;
        } else {
          that.tagID = that.tagID + "|" + item.lid;
        }
      } else {
        that.$message({
          message: "已经选择了",
          type: "warning"
        });
      }
    },
    //发布文章
    btn_postArticle(e) {
      if (e === 2) {
        //    保存文章
        let json = {
          aid: that.aid,
          title: that.title,
          content: that.content,
          label: that.tagID,
          classification: that.categoryButtons,
          status: 1
        };
        that
          .$Axios(that.$store)
          .post(that.ARTICLE_API + "/update", json)
          .then(function(result) {
            that.$router.go(0);
          });
      } else {
        let json = {
          title: that.title,
          content: that.content,
          tagID: that.tagID,
          categoryId: that.categoryButtons,
          status: e
        };

        that
          .$Axios(that.$store)
          .put(that.ARTICLE_API + "/", json)
          .then(function(result) {
            if (e === 1) {
              that.$message({
                message: "发布成功",
                type: "success"
              });
            } else {
              that.$message({
                message: "已经丢到废纸篓了",
                type: "success"
              });
            }
          });
      }
    }
  }
};
</script>

<style scoped src="../../static/md/markdown.css">
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>